'use client'

import { Box, Flex, Text, Tooltip, HStack, Badge, useColorModeValue } from '@chakra-ui/react'
import { Editor } from '@tiptap/react'
import { useEffect, useState } from 'react'
import { useChapterStore } from '@/store/chapterStore'

interface EditorStatusBarProps {
  editor: Editor | null
}

// 计算阅读时间（以分钟为单位）
const calculateReadingTime = (wordCount: number): number => {
  // 中文阅读速度约为每分钟300字
  return Math.ceil(wordCount / 300);
}

const EditorStatusBar = ({ editor }: EditorStatusBarProps) => {
  const bgColor = useColorModeValue('gray.50', 'gray.800')
  const borderColor = useColorModeValue('gray.200', 'gray.700')
  const textColor = useColorModeValue('gray.600', 'gray.300')
  
  const { currentChapter, saveStatus } = useChapterStore()
  const [stats, setStats] = useState({
    characters: 0,
    words: 0,
    sentences: 0,
    paragraphs: 0,
    readingTime: 0,
    lastSaved: ''
  })
  
  // 每当编辑器内容变化时更新统计信息
  useEffect(() => {
    if (!editor) return
    
    const text = editor.getText()
    
    // 计算字符数（不包括空格）
    const characters = text.replace(/\s/g, '').length
    
    // 计算中文字数
    const chineseRegex = /[\u4e00-\u9fa5]/g
    const chineseMatches = text.match(chineseRegex)
    const chineseCount = chineseMatches ? chineseMatches.length : 0
    
    // 计算英文单词数
    const englishText = text.replace(/[\u4e00-\u9fa5]/g, ' ')
    const englishCount = englishText.split(/\s+/).filter(word => word.length > 0).length
    
    // 总词数
    const wordCount = chineseCount + englishCount
    
    // 计算句子数（以句号、问号、感叹号结尾）
    const sentenceCount = (text.match(/[.!?。！？]+/g) || []).length
    
    // 计算段落数
    const paragraphCount = (text.split(/\n+/).filter(para => para.trim().length > 0) || []).length
    
    // 估计阅读时间
    const readingTime = calculateReadingTime(wordCount)
    
    // 最后保存时间
    const lastSaved = currentChapter?.updatedAt 
      ? formatLastSaved(new Date(currentChapter.updatedAt))
      : '未保存'
    
    setStats({
      characters,
      words: wordCount,
      sentences: sentenceCount,
      paragraphs: paragraphCount,
      readingTime,
      lastSaved
    })
    
  }, [editor, currentChapter?.updatedAt])
  
  // 格式化最后保存时间
  const formatLastSaved = (date: Date): string => {
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffMins = Math.floor(diffMs / 60000)
    
    if (diffMins < 1) return '刚刚'
    if (diffMins < 60) return `${diffMins}分钟前`
    
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  }
  
  // 渲染保存状态指示器
  const renderSaveStatus = () => {
    switch(saveStatus) {
      case 'saving':
        return <Badge colorScheme="blue">保存中...</Badge>
      case 'saved':
        return <Badge colorScheme="green">已保存</Badge>
      case 'error':
        return <Badge colorScheme="red">保存失败</Badge>
      default:
        return <Badge colorScheme="gray">未保存</Badge>
    }
  }
  
  if (!editor) {
    return null
  }
  
  return (
    <Box
      p={2}
      bg={bgColor}
      borderTop="1px"
      borderColor={borderColor}
      fontSize="sm"
      color={textColor}
    >
      <Flex justify="space-between" wrap="wrap">
        <HStack spacing={4}>
          <Tooltip label="总字数">
            <Text>{stats.words} 字</Text>
          </Tooltip>
          <Tooltip label="字符数（不含空格）">
            <Text>{stats.characters} 字符</Text>
          </Tooltip>
          <Tooltip label="句子数">
            <Text>{stats.sentences} 句</Text>
          </Tooltip>
          <Tooltip label="段落数">
            <Text>{stats.paragraphs} 段</Text>
          </Tooltip>
          <Tooltip label="预计阅读时间">
            <Text>{stats.readingTime} 分钟阅读</Text>
          </Tooltip>
        </HStack>
        
        <HStack spacing={2}>
          {renderSaveStatus()}
          <Text>{stats.lastSaved}</Text>
        </HStack>
      </Flex>
    </Box>
  )
}

export default EditorStatusBar 